package com.iseastar.guojiang.newcabinet.adapter;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.iseastar.dianxiaosan.model.Const;
import com.iseastar.guojiang.dialog.DialogMgr;
import com.iseastar.guojiang.model.NewParcelBean;
import com.iseastar.guojiang.newcabinet.adapter.NoScrollGridViewAdapter;
import com.iseastar.guojiang.view.NoScrollGridView;
import com.shouhuobao.station.R;
import com.shouhuobao.take.utils.StringUtils;

import java.util.ArrayList;

import droid.frame.activity.base.BaseAdapterExt;
import droid.frame.ui.utils.Utils;
import droid.frame.utils.GlideUtil;

/**
 * 包裹列表适配起
 * Created by lidandan on 2017/12/20.
 */

public class ParcelListAdapter extends BaseAdapterExt<NewParcelBean> {

    private Handler handler;
    private ListView mListView;

    public ParcelListAdapter(ArrayList<NewParcelBean> items, Activity context, ListView listView, Handler handler) {
        super(items, context);
        this.mListView = listView;
        this.handler = handler;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder viewHolder;
        if (convertView == null || convertView.getTag() == null) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.layout_parcel_list_item, parent, false);
            viewHolder.taskNoTV = (TextView) convertView.findViewById(R.id.task_no_tv);
            viewHolder.orderCodeTv = (TextView) convertView.findViewById(R.id.order_code_tv);
            viewHolder.rejectTv = (TextView) convertView.findViewById(R.id.reject_tv);
            viewHolder.packageImage = (ImageView) convertView.findViewById(R.id.package_image);
            viewHolder.postNumberTv = (TextView) convertView.findViewById(R.id.post_number_tv);
            viewHolder.sendCodeTv = (TextView) convertView.findViewById(R.id.send_code_tv);
            viewHolder.openBoxCodeTV = (TextView) convertView.findViewById(R.id.open_box_code_tv);
            viewHolder.goodsInfoTv = (TextView) convertView.findViewById(R.id.goods_info_tv);
            viewHolder.picturesBtn = (TextView) convertView.findViewById(R.id.pictures_btn);
            viewHolder.sweepIv = (ImageView) convertView.findViewById(R.id.sweep_iv);
            viewHolder.picturesTv = (TextView) convertView.findViewById(R.id.pictures_tv);
            viewHolder.gridView = (NoScrollGridView) convertView.findViewById(R.id.grid_view);
            viewHolder.scanLayoutLL = (LinearLayout) convertView.findViewById(R.id.scan_layout_ll);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        final NewParcelBean parcel = items.get(position);
        setDataToView(viewHolder, parcel, position);
        return convertView;
    }

    /**
     * 设置数据到视图
     *
     * @param viewHolder
     * @param parcel
     * @param position
     */
    private void setDataToView(ViewHolder viewHolder, final NewParcelBean parcel, final int position) {
        //根据任务类型进行界面相应的展示和隐藏
        //到柜展示密码失效和开箱密码
        viewHolder.taskNoTV.setVisibility(View.GONE);
        if (Const.CourierTaskStatus.cabinetTask == parcel.getTaskType()) {
            viewHolder.openBoxCodeTV.setVisibility(View.VISIBLE);
            viewHolder.rejectTv.setVisibility(View.VISIBLE);
            viewHolder.rejectTv.setText("密码失效");
            viewHolder.openBoxCodeTV.setText("开箱密码：" + parcel.getPassword2());
            viewHolder.rejectTv.setBackgroundResource(R.drawable.task_contact_sender_phone_6a7584_bg);
            //密码失效
            viewHolder.rejectTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setItemOnClick(4, position, parcel);
                }
            });
        } else {//只有柜子有开箱码，其他的都没有
            viewHolder.openBoxCodeTV.setVisibility(View.GONE);
            //            if (Const.CourierTaskStatus.stationTask == parcel.getTaskType()) {//驿站没有拒收操作
            //                viewHolder.rejectTv.setVisibility(View.GONE);
            //            } else {//上门
            if (Const.CourierTaskStatus.sameCityTask == parcel.getTaskType()) {
                viewHolder.taskNoTV.setVisibility(View.VISIBLE);
                viewHolder.taskNoTV.setText(parcel.getTaskNo());
            }
            viewHolder.rejectTv.setVisibility(View.VISIBLE);
            //已经拒收
            if (parcel.isRejectStatus()) {
                viewHolder.rejectTv.setText("已拒收");
                viewHolder.rejectTv.setBackgroundColor(context.getResources().getColor(R.color.transparent));
            } else {//还没有拒收
                viewHolder.rejectTv.setText("拒收");
                viewHolder.rejectTv.setBackgroundResource(R.drawable.task_contact_sender_phone_6a7584_bg);
            }
            //拒收
            viewHolder.rejectTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //没有拒收过的包裹才可进行操作
                    if (!parcel.isRejectStatus()) {
                        setItemOnClick(1, position, parcel);
                    }
                }
            });
            //            }
        }
        //订单编号
        viewHolder.orderCodeTv.setText("订单编号：" + parcel.getOrderId());
        //加载包裹头像
        GlideUtil.loadImage(context, parcel.getParcelImgUrl(), R.drawable.ic_launcher, viewHolder.packageImage);
        if (!StringUtils.isEmpty(parcel.getParcelImgUrl())) {
            viewHolder.packageImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DialogMgr.showLargeStationPhoto(context, parcel.getParcelImgUrl());
                }
            });
        }
        //投递编号
        if (StringUtils.isEmpty(parcel.getBagCode())) {
            viewHolder.postNumberTv.setText("投递编号：无");
            viewHolder.scanLayoutLL.setVisibility(View.VISIBLE);
            //扫描绑定袋子编号
            viewHolder.scanLayoutLL.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setItemOnClick(3, position, parcel);
                }
            });
        } else {
            viewHolder.scanLayoutLL.setVisibility(View.GONE);
            viewHolder.postNumberTv.setText("投递编号：" + parcel.getBagCode());
        }
        //寄件码
        viewHolder.sendCodeTv.setText("寄件码：" + parcel.getCheckCode());
        //物品信息
        viewHolder.goodsInfoTv.setText("物品信息：" + parcel.getCategory() + "/" + parcel.getWeight() + "kg");
        if (StringUtils.isEmpty(parcel.getBagImg1()) || StringUtils.isEmpty(parcel.getBagImg2()) || StringUtils.isEmpty(parcel.getBagImg3())) {
            viewHolder.picturesBtn.setVisibility(View.VISIBLE);
            //对包裹进行拍照,如果当前包裹有三张图片后，拍照按钮进行隐藏，不能进行拍照
            viewHolder.picturesBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setItemOnClick(2, position, parcel);
                }
            });
        } else {
            viewHolder.picturesBtn.setVisibility(View.INVISIBLE);
        }
        ArrayList<String> imageList = new ArrayList<>();
        if (!StringUtils.isEmpty(parcel.getBagImg1())) {
            imageList.add(parcel.getBagImg1());
        }
        if (!StringUtils.isEmpty(parcel.getBagImg2())) {
            imageList.add(parcel.getBagImg2());
        }
        if (!StringUtils.isEmpty(parcel.getBagImg3())) {
            imageList.add(parcel.getBagImg3());
        }
        if (imageList.size() == 0) {
            viewHolder.gridView.setVisibility(View.GONE);
            viewHolder.picturesTv.setVisibility(View.VISIBLE);
        } else if (imageList.size() == 3) {
            viewHolder.gridView.setVisibility(View.VISIBLE);
            viewHolder.picturesBtn.setVisibility(View.INVISIBLE);
            viewHolder.picturesTv.setVisibility(View.GONE);
        } else {
            viewHolder.picturesBtn.setVisibility(View.VISIBLE);
            viewHolder.gridView.setVisibility(View.VISIBLE);
            viewHolder.picturesTv.setVisibility(View.GONE);
        }
        if (viewHolder.gridView.getAdapter() == null) {
            NoScrollGridViewAdapter adapter = new NoScrollGridViewAdapter(imageList, context, handler, position, parcel);
            viewHolder.gridView.setAdapter(adapter);
        } else {
            NoScrollGridViewAdapter adapter = (NoScrollGridViewAdapter) viewHolder.gridView.getAdapter();
            adapter.setItems(imageList, true);
        }
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) viewHolder.gridView.getLayoutParams();
        if (imageList.size() == 1) {
            params.width = Utils.dpToPx(90, context.getResources());
            viewHolder.gridView.setNumColumns(1);
        } else if (imageList.size() == 2) {
            viewHolder.gridView.setNumColumns(2);
            params.width = Utils.dpToPx(190, context.getResources());
        } else if (imageList.size() == 3) {
            viewHolder.gridView.setNumColumns(3);
            params.width = Utils.dpToPx(300, context.getResources());
        }
        viewHolder.gridView.setLayoutParams(params);
    }

    /**
     * 点击适配器进行操作
     *
     * @param what     0 删除拍照后的图片 1 拒收  2 对包裹进行拍照  3 扫描袋子进行绑定  4 重新获开箱码
     * @param position
     * @param bean
     */
    private void setItemOnClick(int what, int position, NewParcelBean bean) {
        Message message = Message.obtain();
        message.what = what;
        message.arg1 = position;
        message.obj = bean;
        handler.sendMessage(message);
    }

    class ViewHolder {
        TextView taskNoTV;//任务序列号
        TextView orderCodeTv;//订单编号
        TextView rejectTv;//拒收按钮
        ImageView packageImage;//包裹图片
        TextView postNumberTv;//投递编号
        TextView sendCodeTv;//寄件码
        TextView openBoxCodeTV;//开箱码
        TextView goodsInfoTv;//物品信息
        TextView picturesBtn;//拍照按钮
        ImageView sweepIv;//扫描二维码或条形码
        TextView picturesTv;//拍照旁边的文字
        NoScrollGridView gridView;//加载拍照后的图片
        LinearLayout scanLayoutLL;//扫描二维码的布局
    }

    /**
     * 更新局部item
     *
     * @param position
     * @param parcelBean
     */
    public void updateItemView(int position, NewParcelBean parcelBean) {
        //得到第一个可显示控件的位置，
        int visiblePosition = mListView.getFirstVisiblePosition();
        int visibleLastPosi = mListView.getLastVisiblePosition();
        //只有当要更新的view在可见的位置时才更新，不可见时，跳过不更新
        if (position >= visiblePosition && position <= visibleLastPosi) {
            int index = position - visiblePosition;
            if (index >= 0) {
                //得到要更新的item的view
                View view = mListView.getChildAt(index);
                //从view中取得holder
                ViewHolder holder = (ViewHolder) view.getTag();
                //更改状态
                setDataToView(holder, parcelBean, position);
                //直接更改数据源
                getItems().remove(position);
                getItems().add(position, parcelBean);
            }
        } else {
            //直接更改数据源
            getItems().remove(position);
            getItems().add(position, parcelBean);
        }
    }
}
